import React from 'react';
import PropTypes from 'prop-types';//react 16.X这样用，改动太大，升级困难
import { DaysOfMonth } from '../const';

class Day extends React.Component {
    constructor(props) {
        super(props);
    }

    static propTypes = {
        onChange: PropTypes.func.isRequired,
        day: PropTypes.string,
        month: PropTypes.string.isRequired,
        year: PropTypes.string.isRequired,
    }

    static defaultProps = {
        day: '',
    }

    state = {
        arr: new Array(30),//这样设置，react是不会渲染的，因为内容为空
    }

    initState(year, month) {
        const arr = [''];
        let length;
        if (!month) {
            length = 0;
        } else {
            length = DaysOfMonth[month - 1];
        }
        for (let i = 0; i < length; i++) {
            arr.push(i + 1)
        }
        this.setState({
            arr
        });
        if (!month) {
            this.props.onChange('');
        }
    }

    componentWillMount() {
        this.initState(this.props.year, this.props.month);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.day === this.props.day && nextProps.year === this.props.year && nextProps.month === this.props.month) {
            return;
        }
        this.initState(nextProps.year, nextProps.month);
    }

    onChange = (e) => {
        const value = e.target.value;
        if (value === this.props.day) {
            return;
        }
        this.props.onChange(value);
    }

    render() {

        return (<select onChange={this.onChange} value={this.props.day}>
            {
                this.state.arr.map((item, index, arr) => {
                    return (<option key={index} value={item}>{item ? item : '请选择'}</option>)
                })
            }
        </select>);
    }
}

export default Day;
